/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package utils;

import database.ConnectionUtil;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Valentina
 */
public class TestUtil {
    
    public static int getRowsCount(String tableName, String fieldName){
        
        int rows =0 ;
        String SQL_FIND = "SELECT count("+fieldName+") FROM "+tableName;

        Connection con = ConnectionUtil.getConnection();
        
        try {
            con.setAutoCommit(false);

            Statement stmt = con.createStatement();

            //stmt.setString(1, fieldName);
            //stmt.setString(2, tableName);

            ResultSet rs = stmt.executeQuery(SQL_FIND);
            if (rs.next()) {
                rows = rs.getInt(1);
            }

            con.commit();
        } catch (Exception e) {

            rows = 0;
            System.err.println("Find RowsCount Error !" + e);
            try {
                con.rollback();
            } catch (SQLException ex) {
                Logger.getLogger(TestUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return rows;
    }

    public static int getRowsCountByColumn(String tableName, String fieldName, String columnName, Long columnID){

        int rows =0 ;
        String SQL_FIND = "SELECT count("+fieldName+") FROM "+tableName+" WHERE "+columnName+" = "+columnID;

        Connection con = ConnectionUtil.getConnection();

        try {
            con.setAutoCommit(false);

            Statement stmt = con.createStatement();

            ResultSet rs = stmt.executeQuery(SQL_FIND);
            if (rs.next()) {
                rows = rs.getInt(1);
            }

            con.commit();
        } catch (Exception e) {

            rows = 0;
            System.err.println("Find RowsCount Error !" + e);
            try {
                con.rollback();
            } catch (SQLException ex) {
                Logger.getLogger(TestUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return rows;
    }

    public static void main(String[] args) {
        String tableName = "vo";
        String filedName = "id_vo";
        int rows = TestUtil.getRowsCount(tableName, filedName);

        System.out.println("Tabela "+ tableName+" are "+ rows+" rinduri");
    }

}
